<?php
/**
 * @author:ivan
 * Time: 2015/12/2 12:44
 */

namespace App\Http\Controllers\Auth;


use App\Http\Controllers\Advice\AdviceController;
use App\Http\Controllers\UserController;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Input;
use Validator;
use Illuminate\Support\Facades\Auth;

class RegisterController extends Controller
{
    private $userController;

    private $loginPath;

    private $adviceC;

    /**
     * RegisterController constructor.
     */
    public function __construct()
    {
        $this->loginPath='login';
        $this->userController=new UserController();
        $this->adviceC=new AdviceController();
    }


    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getRegister()
    {
        return view('register');
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postRegister(Request $request)
    {
        $data=$request->all();
        $data['type']=0;
        $validator = $this->validator($data);

        if ($validator->fails()) {

            return redirect()->back()->withErrors($validator->getMessageBag());
        }

        if($this->userController->find($data['name'])->count()!=0)
        {
            return redirect()->back()->withErrors(['msg'=>'The username already exists!']);
           // return response()->json(array('msg',"The username ..."));

        }
        $this->adviceC->distributeAdviser($data['name']);       //为其分配教练和医生
        Auth::login($this->userController->store($data));
        return redirect($this->loginPath);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    private function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'password' => 'required|confirmed|min:6',
            'password_confirmation' => 'required'
        ]);
    }

    /**
     * check if username exists via ajax
     *
     * @return \Illuminate\Http\Response
     */
    public function checkUsername(){
        if($this->userController->find(Input::get('name'))->count()!=0)
       {
           return response()->json(array(
               'status' => 0,
            'msg' => 'The username already exists',
            ));
       }else{
            return response()->json(array(
                'status' => 1,
                'msg' => 'ok',
            ));
        }
    }

}